#!/bin/bash

# 运行鸿蒙一键构建部署脚本（多 HSP 包模式）
# 使用前请确保 hdc 已连接设备，DevEco Studio 工具链已安装

set -e

# ================== 可配置变量 ==================
# 项目包名(根据实际项目包名修改!!!!!)
BUNDLE_NAME="com.itcast.mk_shop"
# ================== 可配置变量 ==================

# ================== 固定的变量 ==================
# 临时目录名（使用随机字符串避免冲突）
TMP_DIR="hm_deploy_tmp_$(openssl rand -hex 16)"
# HSP 和 HAP 包路径
BASIC_HSP="commons/basic/build/default/outputs/default/basic-default-signed.hsp"
PHONE_HAP="products/phone/build/default/outputs/default/phone-default-signed.hap"
MINE_HSP="features/mine/build/default/outputs/default/mine-default-signed.hsp"
HOME_HSP="features/home/build/default/outputs/default/home-default-signed.hsp"
CATEGORY_HSP="features/category/build/default/outputs/default/category-default-signed.hsp"
CART_HSP="features/cart/build/default/outputs/default/cart-default-signed.hsp"
# ================== 固定的变量 ==================

echo "1. 安装依赖..."
ohpm install --all --registry https://ohpm.openharmony.cn/ohpm/ --strict_ssl true

echo "2. 构建项目..."
hvigorw assembleApp

echo "3. 停止正在运行的应用..."
hdc shell aa force-stop $BUNDLE_NAME || true

echo "4. 创建设备临时目录..."
hdc shell mkdir -p data/local/tmp/$TMP_DIR

echo "5. 传输 HSP 和 HAP 包到设备..."
# 传输基础模块 HSP
echo "  - 传输 basic.hsp..."
hdc file send $BASIC_HSP "data/local/tmp/$TMP_DIR"

# 传输 phone HAP
echo "  - 传输 phone.hap..."
hdc file send $PHONE_HAP "data/local/tmp/$TMP_DIR"

# 传输 mine/cart/category/home HSP
echo "  - 传输 mine.hsp..."
hdc file send $MINE_HSP "data/local/tmp/$TMP_DIR"
echo "  - 传输 cart.hsp..."
hdc file send $CART_HSP "data/local/tmp/$TMP_DIR"
echo "  - 传输 category.hsp..."
hdc file send $CATEGORY_HSP "data/local/tmp/$TMP_DIR"
echo "  - 传输 home.hsp..."
hdc file send $HOME_HSP "data/local/tmp/$TMP_DIR"

echo "6. 安装应用包..."
hdc shell bm install -p data/local/tmp/$TMP_DIR

echo "7. 清理设备临时文件..."
hdc shell rm -rf data/local/tmp/$TMP_DIR

echo "8. 启动应用..."
hdc shell aa start -a EntryAbility -b $BUNDLE_NAME -m phone

echo "✅ 构建部署完成！应用已成功启动"